Random Examples
Gists
Gists2

Given an integer n, return any array containing n unique integers such that they add up to 0.

1
# Example 1: Input: n = 5 | Output: [-7,-1,1,3,4]
2
# Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
3
# Example 2: Input: n = 3 | Output: [-1,0,1]
4
# Example 3: Input: n = 1 | Output: [0]
Copied!
1
# Constraints: 1 <= n <= 1000
Copied!
1
## time complexity: O(1 or n)
2
## space complexity: O(1)
3
4
5
def sumZero(self, n: int):
6
"""
7
:type n: int
8
:rtype: List[int]
9
"""
10
# time complexity: O(1); create one range of digits
11
# space complexity: O(1); one unit of space
12
13
# What's going on here? Let's say n = 5.
14
# Return a range of numbers which starts at 1-5, ends at 5, steps every 2
15
# So that means it starts at -4, ends at 5, steps every 2
16
# And it would return: [-4, -2, 0, 2, 4]
17
18
return range(1 - n, n, 2)
Copied!
1
# Min Moves to Obtain String Without 3 Identical Consecutive Letters
Copied!
1
# You are given a string S consisting of N letters ‘a’ and/or ‘b’.
2
# In one move, you can swap one letter for the other (‘a’ for ‘b’ or ‘b’ for ‘a’).
3
# Write a function solution that, given such a string S, returns the minimum number
4
# of moves required to obtain a string containing no instances of three identical
5
# consecutive letters.
Copied!
1
# time complexity: O(n) because of the one while loop
2
# space complexity: O(1) since this all takes up only one unit of space
3
4
5
def calculate_current_moves(start_sub, end_sub):
6
sub_length = end_sub - start_sub
7
# get current number of moves to add to total
8
current_moves = sub_length // 3
9
# add current number of moves to total
10
return current_moves
11
12
13
def calculate_min_moves(string):
14
# initialize start and end of first possible subsequence
15
start_sub = 0
16
end_sub = 1
17
# initialize counter for number of moves
18
moves = 0
19
# initialize string length
20
length = len(string)
21
22
# loop until index of subsequence end gets to end of string
23
while end_sub < length:
24
# if index of subsequence end is at least one after start
25
if string[end_sub] != string[start_sub]:
26
# add current number of moves to total
27
moves += calculate_current_moves(start_sub, end_sub)
28
# move to end of current subsequence
29
start_sub = end_sub
30
# new end of subsequence = 1 after current start
31
end_sub += 1
32
33
# in cases where sub-sequence ends the string
34
# add current number of moves to total
35
moves += calculate_current_moves(start_sub, end_sub)
36
37
return moves
Copied!
1
# checks whether IP digits are valid or not
2
def is_valid(possible_ip):
3
4
# splitting at period
5
ip_address = possible_ip.split(".")
6
7
# checking for corner cases
8
for subaddress in ip_address:
9
10
# get length of subaddress
11
length_subaddress = len(subaddress)
12
# get int of subaddress
13
int_subaddress = int(subaddress)
14
# get first digit of subaddress
15
first_digit = subaddress[0]
16
17
# if length > 3 OR subaddress int is outside 0-255 OR
18
# if length > 1 AND subaddress int is 0 OR
19
# if length > 1 AND subaddress int is NOT 0 and first digit is 0
20
# return false for invalid ip
21
if length_subaddress > 3 or int_subaddress < 0 or int_subaddress > 255:
22
return False
23
elif length_subaddress > 1 and int_subaddress is 0:
24
return False
25
elif length_subaddress > 1 and int_subaddress is not 0 and first_digit is "0":
26
return False
27
28
# else return true for valid ip
29
return True
Copied!
1
# converts string to IP address
2
def convert_string_to_ip(string):
3
4
# get string length
5
length = len(string)
6
7
# if string of digits > 12, it's not an IP; return empty array
8
if length > 12:
9
return []
10
11
# else set current possible ip as string AND
12
current_possible_ip = string
13
# initialize empty valid ip list
14
valid_ip_list = []
15
16
# loop through possible ips:
17
# first period loop
18
for i in range(1, length - 2):
19
# second period loop
20
for j in range(i + 1, length - 1):
21
# third period loop
22
for k in range(j + 1, length):
23
24
# add first period to ip to check
25
begin_to_k = current_possible_ip[:k]
26
k_to_end = current_possible_ip[k:]
27
current_possible_ip = begin_to_k + "." + k_to_end
28
29
# add second period to ip to check
30
begin_to_j = current_possible_ip[:j]
31
j_to_end = current_possible_ip[j:]
32
current_possible_ip = begin_to_j + "." + j_to_end
33
34
# add third period to ip to check
35
begin_to_i = current_possible_ip[:i]
36
i_to_end = current_possible_ip[i:]
37
current_possible_ip = begin_to_i + "." + i_to_end
38
39
# if current combination is valid, add to valid ip list
40
is_ip_valid = is_valid(current_possible_ip)
41
if is_ip_valid:
42
valid_ip_list.append(current_possible_ip)
43
44
# reset current possible id to original string before looping again
45
current_possible_ip = string
46
47
# return valid ip list
48
return valid_ip_list
49
50
51
A = "25525511135"
52
# B = "25505011535"
53
print(convert_string_to_ip(A))
54
# print(convert_string_to_ip(B))
Copied!
1
# Given a string, what is the minimum number of adjacent swaps required to convert a string into
2
# a palindrome.
3
# If not possible, return -1.
4
5
"""
6
Example 1: Input: "mamad" | Output: 3
7
Example 2: Input: "asflkj" | Output: -1
8
Example 3: Input: "aabb" | Output: 2
9
Example 4: Input: "ntiin" | Output: 1
10
Explanation: swap 't' with 'i' => "nitin"
11
"""
Copied!
1
# time complexity: O(n^2)
2
# space complexity: O(1)
3
4
5
def min_swap(string):
6
# convert string to list
7
list_of_string = list(string)
8
# check if list_of_string can be palindrome
9
odd = 0
10
letter = [0] * 26
11
12
for i in list_of_string:
13
# get unicode char of current letter
14
unicode_i = ord(i)
15
# get unicode char of letter 'a'
16
unicode_a = ord("a")
17
# get alphabet index
18
alphabet_index = unicode_i - unicode_a
19
# get current letter count for each letter in string
20
letter[alphabet_index] += 1
21
22
for l in letter:
23
if l & 1 == 1:
24
odd += 1
25
26
if odd > 1:
27
return -1
28
29
i, j, res = 0, len(list_of_string) - 1, 0
30
31
while i < j:
32
if list_of_string[i] == list_of_string[j]:
33
i, j = i + 1, j - 1
34
continue
35
t = j - 1
36
37
# find same letter with list_of_string[i] from right to left
38
while t > i and list_of_string[t] != list_of_string[i]:
39
t -= 1
40
41
# if t == i, means this is the only letter in the list_of_string, should be swap to the middle
42
# otherwise should be swap to the position of j
43
44
target = len(list_of_string) // 2 if t == i else j
45
46
while t < target:
47
# swap
48
tmp = list_of_string[t]
49
list_of_string[t] = list_of_string[t + 1]
50
list_of_string[t + 1] = tmp
51
res, t = res + 1, t + 1
52
53
return res
54
55
56
print(min_swap("racecra"))
Copied!
1
# Longest Substring Without 3 Contiguous Occurrences of Letter
Copied!
1
# Given a string s containing only a and b, find longest substring of s such that
2
# s does not contain more than two contiguous occurrences of a and b.
Copied!
1
## time complexity: O(n)
2
## space complexity: O(1)
3
4
"""
5
Example 1: Input: "aabbaaaaabb" | Output: "aabbaa"
6
Example 2: Input: "aabbaabbaabbaa" | Output: "aabbaabbaabbaa"
7
"""
8
9
10
def longest_substring(s):
11
# initialize final string
12
final_string = ""
13
length = len(s)
14
x = 0
15
# loop through s
16
while len(s) >= 2:
17
beginning = s[0]
18
middle = s[1]
19
if len(s) > 2:
20
end = s[2]
21
# if current index + 1 != value of current index
22
if beginning != middle:
23
# add value of current index to final string
24
final_string = final_string + beginning
25
# if current index + 1 == value of current index
26
elif beginning == middle:
27
# check current index + 2
28
# if current index + 2 == value of current index
29
if beginning == end:
30
# add value of current & current + 1 to final string
31
final_string = final_string + beginning + middle
32
# return string
33
return final_string
34
# if current index + 2 != value of current index
35
else:
36
# add value of current & current + 1 to final string
37
final_string = final_string + beginning + middle
38
# add 1 to index
39
s = s[2:]
40
elif len(s) == 2:
41
final_string = final_string + beginning + middle
42
# return string
43
return final_string
Copied!
1
## aabbaa
2
print(longest_substring("aabbaaaaabb"))
3
## aabbaabbaabbaa
4
print(longest_substring("aabbaabbaabbaa"))
Copied!
1
# Mixed sorting
2
3
"""
4
Given a list of integers nums, sort the array such that:
5
6
All even numbers are sorted in increasing order
7
All odd numbers are sorted in decreasing order
8
The relative positions of the even and odd numbers remain the same
9
Example 1
10
Input
11
12
nums = [8, 13, 11, 90, -5, 4]
13
Output
14
15
[4, 13, 11, 8, -5, 90]
16
Explanation
17
18
The even numbers are sorted in increasing order, the odd numbers are sorted in
19
decreasing number, and the relative positions were
20
[even, odd, odd, even, odd, even] and remain the same after sorting.
21
"""
Copied!
1
# solution
2
3
import unittest
4
5
6
def mixed_sorting(nums):
7
positions = []
8
odd = []
9
even = []
10
sorted_list = []
11
for i in nums:
12
if i % 2 == 0:
13
even.append(i)
14
positions.append("E")
15
else:
16
odd.append(i)
17
positions.append("O")
18
even.sort()
19
odd.sort()
20
odd.reverse()
21
j, k = 0, 0
22
for i in range(len(nums)):
23
if positions[i] == "E":
24
while j < len(even):
25
sorted_list.append(even[j])
26
j += 1
27
break
28
else:
29
while k < len(odd):
30
sorted_list.append(odd[k])
31
k += 1
32
break
33
34
return sorted_list
Copied!
1
# Lexicographically Smallest String
Copied!
1
# Lexicographically smallest string formed by removing at most
2
# one character.
Copied!
1
# Example 1: Input: "abczd" | Output: "abcd"
Copied!
1
## time complexity: O(n)
2
## space complexity: O(1)
3
4
5
def lexi_smallest(s):
6
length = len(s)
7
length_one_short = length - 1
8
9
for x in range(length_one_short):
10
i_one_short = x - 1
11
x_one_long = x + 1
12
if s[x] > s[x_one_long]:
13
return s[:x] + s[x_one_long:]
14
return s[:-1]
Copied!
1
# abcd
2
print(lexi_smallest("abczd"))
Copied!
1
# String Without 3 Identical Consecutive Letters
Copied!
1
# Write a function solution that, given a string S of N lowercase English letters,
2
# returns a string with no instances of three identical consecutive letters,
3
# obtained from S by deleting the minimum possible number of letters.
4
5
"""
6
Examples:
7
Given S = “eedaaad” , the function should return “eedaad” . One occurrence of letter a is deleted.
8
Given S = “xxxtxxx” , the function should return “xxtxx” . Note that letter x can occur more than three times in the returned string, if the occurrences are not consecutive.
9
Given S = “uuuuxaaaaxuuu” , the function should return “uuxaaxuu”.
10
"""
Copied!
1
# Write an efficient algorithm for the following assumptions:
2
# N is an integer within the range [1..200,000]
3
# string S consists only of lowercase letters (a-z)
Copied!
1
## time complexity: O(n)
2
## space complexity: O(1)
3
4
5
def no_three_consecutive(s):
6
final_string = s[0:2]
7
length = len(s)
8
# loop through original string
9
for x in range(2, length):
10
string_x = s[x]
11
string_x_one_short = s[x - 1]
12
string_x_two_short = s[x - 2]
13
if string_x == string_x_one_short and string_x == string_x_two_short:
14
# don't append if previous chars are same
15
continue
16
else:
17
final_string += string_x
18
return final_string
Copied!
1
# eedaad
2
print(no_three_consecutive("eedaaad"))
Copied!
1
# xxtxx
2
print(no_three_consecutive("xxxtxxx"))
Copied!
1
# uuxaaxuu
2
print(no_three_consecutive("uuuuxaaaaxuuu"))
Copied!
1
# You are given a string s of length n containing only characters a and b.
2
# A substring of s called a semi-alternating substring if it does not
3
# contain three identical consecutive characters.
4
# Return the length of the longest semi-alternating substring.
Copied!
1
# Example 1: Input: "baaabbabbb" | Output: 7
2
# Explanation: "aabbabb"
3
# Example 2: Input: "abaaaa" | Output: 4
4
# Explanation: "abaa"
Copied!
1
# time complexity: O(n)
2
# space complexity: O(1)
3
4
5
def longest_semialternating_ss(s):
6
length = len(s)
7
if not s or length == 0:
8
return 0
9
10
if length < 3:
11
return length
12
13
beginning = 0
14
end = 1
15
# first character
16
comparison_char = s[0]
17
# count the occurrence of the first char
18
count_first_char = 1
19
max_length = 1
20
21
while end < length:
22
end_char = s[end]
23
if end_char == comparison_char:
24
# add one to char count
25
count_first_char += 1
26
# if char found at least two times
27
if count_first_char == 2:
28
x = end - beginning + 1
29
if x > max_length:
30
max_length = x
31
elif count_first_char > 2:
32
# reset beginning pointer
33
beginning = end - 1
34
else:
35
comparison_char = end_char
36
count_first_char = 1
37
if end - beginning + 1 > max_length:
38
max_length = end - beginning + 1
39
end += 1
40
41
return max_length
Copied!
1
# alternate solution
2
def longest_semi(s):
3
max_length = 0
4
left = 0
5
for right in range(len(s)):
6
if right - left + 1 >= 3 and s[right] == s[right - 1] == s[right - 2]:
7
left = right - 1
8
max_length = max(max_length, right - left + 1)
9
return max_length
Copied!
1
# 7
2
print(longest_semialternating_ss("baaabbabbb"))
Copied!
1
# 4
2
print(longest_semialternating_ss("abaaaa"))
Copied!
1
# Alexa is given n piles of equal or unequal heights.
2
# In one step, Alexa can remove any number of boxes from
3
# the pile which has the maximum height and try to make
4
# it equal to the one which is just lower than the maximum
5
# height of the stack.
6
# Determine the minimum number of steps required to make all of
7
# the piles equal in height.
Copied!
1
# Example 1: Input: piles = [5, 2, 1] | Output: 3
2
3
"""
4
Explanation:
5
6
Step 1: reducing 5 -> 2 [2, 2, 1]
7
Step 2: reducing 2 -> 1 [2, 1, 1]
8
Step 3: reducing 2 -> 1 [1, 1, 1]
9
10
So final number of steps required is 3.
11
"""
Copied!
1
## time complexity: O(n)
2
## space complexity: O(1)
3
4
5
def min_steps_equal_piles(piles):
6
steps = 0
7
length = len(piles)
8
if piles == []:
9
return 0
10
else:
11
# get sorted list
12
sorted_piles = set(piles)
13
sorted_piles = sorted(sorted_piles)
14
# get min, max and 2nd max
15
minimum = sorted_piles[0]
16
second_largest = sorted_piles[-2]
17
max_pile = sorted_piles[-1]
18
# subtract from max to equal 2nd max
19
# repeat until all equal second max
20
for x in range(length):
21
if piles[x] == max_pile:
22
difference = max_pile - second_largest
23
piles[x] = piles[x] - difference
24
steps += 1
25
# loop again to make second max equal to min
26
for x in range(length):
27
if piles[x] != minimum:
28
difference = piles[x] - minimum
29
piles[x] = piles[x] - difference
30
steps += 1
31
# return # of steps
32
return steps
Copied!
1
# 3
2
print(min_steps_equal_piles([5, 2, 1]))
Copied!
1
# Day of Week That Is k Days Later
Copied!
1
# Days of the week are represented as three-letter strings.
2
# "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
3
# Write a javaScript function solution that, given a string
4
# S representing the day of the week and an integer K
5
# (between 0 and 500), returns the day of the week that
6
# is K days later.
Copied!
1
# For example, given S = "Wed" and K = 2, the function
2
# should return "Fri".
3
# Given S = "Sat" and K = 23, the function should return
4
# "Mon".
Copied!
1
## time complexity: O(1)
2
## space complexity: O(1)
3
4
5
def k_days_later(s, k):
6
days_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
7
remainder = k % 7
8
s_index = days_of_week.index(s)
9
move_forward = remainder + s_index
10
if move_forward < 7:
11
return days_of_week[move_forward]
12
else:
13
correct_day_index = move_forward - 7
14
return days_of_week[correct_day_index]
Copied!
1
# 0
2
print(k_days_later("Wed", 2))
3
print("----")
4
# 2
5
print(k_days_later("Sat", 23))
6
print("----")
7
print(k_days_later("Sat", 300))
Copied!
1
# Max Inserts to Obtain String Without 3 Consecutive 'a'
Copied!
1
# Write a function solution that, given a string S
2
# consisting of N characters, returns the maximum
3
# number of letters 'a' that can be inserted into
4
# S (including at the front and end of S) so that
5
# the resulting string doesn't contain 3 consecutive
6
# letters 'a'.
Copied!
1
# If string S already contains the substring "aaa", then
2
# your function should return -1.
3
4
"""
5
Examples:
6
1. Given S = "aabab", the function should return 3,
7
because a string "aabaabaa" can be made.
8
2. Given S = "dog", the function should return 8,
9
because a string "aadaaoaagaa" can be made.
10
3. Given S = "aa", the function should return 0,
11
because no longer string can be made.
12
4. Given S= "baaaa", the function should return -1,
13
because there is a substring "aaa".
14
"""
Copied!
1
## time complexity: O()
2
## space complexity: O()
Copied!
1
# Rotting Oranges
2
# https://leetcode.com/problems/rotting-oranges/
Copied!
1
# In a given grid, each cell can have one of three values:
Copied!
1
# the value 0 representing an empty cell;
2
# the value 1 representing a fresh orange;
3
# the value 2 representing a rotten orange.
Copied!
1
# Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Copied!
1
# Return the minimum number of minutes that must elapse until no cell has a fresh orange.
2
# If this is impossible, return -1 instead.
Copied!
1
# Input: [[2,1,1],[1,1,0],[0,1,1]]
2
# Output: 4
Copied!
1
# Input: [[2,1,1],[0,1,1],[1,0,1]]
2
# Output: -1
3
# Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only
4
# happens 4-directionally.
Copied!
1
# Input: [[0,2]]
2
# Output: 0
3
# Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Copied!
1
# 1 <= grid.length <= 10
2
# 1 <= grid[0].length <= 10
3
# grid[i][j] is only 0, 1, or 2
4
5
6
def oranges_rotting(grid):
7
minute_count = 0
8
9
def create_set(grid, target_value):
10
result = set()
11
for y in range(len(grid)):
12
for x in range(len(grid[0])):
13
if grid[y][x] == target_value:
14
result.add((x, y))
15
return result
16
17
# create a set of rotten & fresh orange locations
18
rotten_os = create_set(grid, 2)
19
fresh_oranges = create_set(grid, 1)
20
21
length_fresh = len(fresh_oranges)
22
23
# For each time interval iteration
24
while length_fresh > 0:
25
going_bad = set()
26
# loop through fresh oranges and create a set going bad
27
for x, y in fresh_oranges:
28
up_cell = (x - 1, y)
29
down_cell = (x + 1, y)
30
left_cell = (x, y - 1)
31
right_cell = (x, y + 1)
32
if (
33
up_cell in rotten_os
34
or down_cell in rotten_os
35
or left_cell in rotten_os
36
or right_cell in rotten_os
37
):
38
currently_going_bad = (x, y)
39
going_bad.add(currently_going_bad)
40
41
# if none are going bad, it's impossible
42
length_gb = len(going_bad)
43
if length_gb == 0:
44
return -1
45
46
# remove oranges going bad from fresh and add to rotten
47
fresh_oranges.difference_update(going_bad)
48
rotten_os.update(going_bad)
49
50
minute_count += 1
51
length_fresh = len(fresh_oranges)
52
53
return minute_count
Copied!
1
# 4
2
grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]
3
print(oranges_rotting(grid))
Copied!
1
# -1
2
grid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]
3
print(oranges_rotting(grid))
Copied!
1
# 0
2
grid = [[0, 2]]
3
print(oranges_rotting(grid))
4
5
import turtle
6
t = turtle.Turtle()
7
t.circle(20)
8
t1=turtle.Turtle()
9
t1.circle(25)
Copied!
1
# Milk Bottles
2
# https://leetcode.com/discuss/interview-question/707939/Microsoft-or-Azure-or-Milk-Bottles
Copied!
1
# If i can exchange 3 empty bottles for one full bottle, given that i have 18 full milk bottles
2
# initially, how many milk bottles can i drink?
Copied!
1
# Generalize this for 'n' bottles
2
3
4
def bottles(n):
5
bottles_to_drink = int((3 * n - 1) / 2)
6
return bottles_to_drink
7
8
9
print(bottles(18))
Copied!
1
# find the largest BST subtree in a given binary tree
2
# https://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
Copied!
1
# Given a Binary Tree, write a function that returns the size of the largest subtree which
2
# is also a Binary Search Tree (BST).
Copied!
1
# If the complete Binary Tree is BST, then return the size of whole tree.
2
3
4
class BinarySearchTree:
5
def __init__(self, value):
6
self.value = value
7
self.left = None
8
self.right = None
9
10
def largest_BST(self):
11
# Set the initial values for calling
12
# largestBSTUtil()
13
Min = [999999999999] # For minimum value in right subtree
14
Max = [-999999999999] # For maximum value in left subtree
15
16
max_size = [0] # For size of the largest BST
17
is_bst = [0]
18
19
largestBSTUtil(node, Min, Max, max_size, is_bst)
20
21
return max_size[0]
22
23
# largestBSTUtil() updates max_size_ref[0]
24
# for the size of the largest BST subtree.
25
# Also, if the tree rooted with node is
26
# non-empty and a BST, then returns size of
27
# the tree. Otherwise returns 0.
28
def largestBSTUtil(node, min_ref, max_ref, max_size_ref, is_bst_ref):
29
30
# Base Case
31
if node == None:
32
is_bst_ref[0] = 1 # An empty tree is BST
33
return 0 # Size of the BST is 0
34
35
Min = 999999999999
36
37
# A flag variable for left subtree property
38
# i.e., max(root.left) < root.data
39
left_flag = False
40
41
# A flag variable for right subtree property
42
# i.e., min(root.right) > root.data
43
right_flag = False
44
45
ls, rs = 0, 0 # To store sizes of left and
46
# right subtrees
47
48
# Following tasks are done by recursive
49
# call for left subtree
50
# a) Get the maximum value in left subtree
51
# (Stored in max_ref[0])
52
# b) Check whether Left Subtree is BST or
53
# not (Stored in is_bst_ref[0])
54
# c) Get the size of maximum size BST in
55
# left subtree (updates max_size[0])
56
max_ref[0] = -999999999999
57
ls = largestBSTUtil(node.left, min_ref, max_ref, max_size_ref, is_bst_ref)
58
if is_bst_ref[0] == 1 and node.data > max_ref[0]:
59
left_flag = True
60
61
# Before updating min_ref[0], store the min
62
# value in left subtree. So that we have the
63
# correct minimum value for this subtree
64
Min = min_ref[0]
65
66
# The following recursive call does similar
67
# (similar to left subtree) task for right subtree
68
min_ref[0] = 999999999999
69
rs = largestBSTUtil(node.right, min_ref, max_ref, max_size_ref, is_bst_ref)
70
if is_bst_ref[0] == 1 and node.data < min_ref[0]:
71
right_flag = True
72
73
# Update min and max values for the
74
# parent recursive calls
75
if Min < min_ref[0]:
76
min_ref[0] = Min
77
if node.data < min_ref[0]: # For leaf nodes
78
min_ref[0] = node.data
79
if node.data > max_ref[0]:
80
max_ref[0] = node.data
81
82
# If both left and right subtrees are BST.
83
# And left and right subtree properties hold
84
# for this node, then this tree is BST.
85
# So return the size of this tree
86
if left_flag and right_flag:
87
if ls + rs + 1 > max_size_ref[0]:
88
max_size_ref[0] = ls + rs + 1
89
return ls + rs + 1
90
else:
91
92
# Since this subtree is not BST, set is_bst
93
# flag for parent calls is_bst_ref[0] = 0;
94
return 0
Copied!
1
# Driver Code
2
if __name__ == "__main__":
3
4
# Let us construct the following Tree
5
# 50
6
# / \
7
# 10 60
8
# / \ / \
9
# 5 20 55 70
10
# / / \
11
# 45 65 80
12
root = newNode(50)
13
root.left = newNode(10)
14
root.right = newNode(60)
15
root.left.left = newNode(5)
16
root.left.right = newNode(20)
17
root.right.left = newNode(55)
18
root.right.left.left = newNode(45)
19
root.right.right = newNode(70)
20
root.right.right.left = newNode(65)
21
root.right.right.right = newNode(80)
Copied!
1
# The complete tree is not BST as 45 is in
2
# right subtree of 50. The following subtree
3
# is the largest BST
4
# 60
5
# / \
6
# 55 70
7
# / / \
8
# 45 65 80
9
10
print("Size of the largest BST is", largestBST(root))
Copied!
1
# This code is contributed by PranchalK
Copied!
1
# Return Strings That Do Not Contain Identical Neighbors
Copied!
1
# Consider all words of length N, consisting only of letters "b' and/or "c",
2
# that do not contain two identical neighbouring letters.
3
# For example, "aba' is such a word but "abb" is not (two letters "b" occur
4
# next to each other).
5
# We are interested in finding the K alphabetically smallest words of length
6
# N that do not contain two identical neighbouring letters.
7
# For example, the first four words consisting of two letters are: "ab',
8
# "ac•, "ba", "bc•.
9
# All correct two-letters words are: "ab", "ac", "ba•, "bc", "ca•, "cb".
Copied!
1
# Find and fix bug(s) in a given implementation of a function:
Copied!
1
# class Solution { public String[] solution(int N, int K) }
Copied!
1
# that, given integers N and K, retums an array of strings: the first
2
# K words of the alphabetically sorted sequence of words of length
3
# N, in which no two neighbouring letters are the same. If K is
4
# bigger than the sequence's length, the entire sequence is returned.
Copied!
1
# Examples:
2
# 1 . Given N = 2 and K = 4, the function should retum tab", "ac", "ban,
3
# 'bc'] as explained above.
4
# 2. Given N = 3 and K = 20, the function should retum ['aba", •abc",
5
# •aca", •acb", "bab", "bac", 'bca", "bcb', "cab", •cac•, "cba",
6
# "cbcl.
7
# 3. Given N = 5 and K = 6, the function should retum ['ababa", "ababc•,
8
# "abaca', "abacb", "abcab", •abcac"].
Copied!
1
# The attached code is still incorrect for some inputs.
2
# Despite the error(s), the code may produce a correct answer for the
3
# example test cases.
4
# The goal of the exercise is to find and fix the bug(s) in the
5
# implementation.
6
# You can modify at most two lines.
Copied!
1
# Assume that:
2
# N is an integer within the range [1..101;
3
# K is an integer within the range [1..100].
Copied!
1
# In your solution, focus on correctness.
2
3
"""
4
Find the size of longest subset of A, in which
5
any 2 elements' different is divisible by M.
6
"""
7
8
t = turtle.Turtle()
9
t.circle(50)
10
11
"""
12
Problem:
13
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor
14
of a given number N?
15
16
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
17
"""
Copied!
1
# def solution(n: int) -> int:
2
def solution(n: int = 600851475143) -> int:
3
"""Returns the largest prime factor of a given number n.
4
>>> solution(13195)
5
29
6
>>> solution(10)
7
5
8
>>> solution(17)
9
17
10
>>> solution(3.4)
11
3
12
>>> solution(0)
13
Traceback (most recent call last):
14
...
15
ValueError: Parameter n must be greater or equal to one.
16
>>> solution(-17)
17
Traceback (most recent call last):
18
...
19
ValueError: Parameter n must be greater or equal to one.
20
>>> solution([])
21
Traceback (most recent call last):
22
...
23
TypeError: Parameter n must be int or passive of cast to int.
24
>>> solution("asd")
25
Traceback (most recent call last):
26
...
27
TypeError: Parameter n must be int or passive of cast to int.
28
"""
29
try:
30
n = int(n)
31
except (TypeError, ValueError):
32
raise TypeError("Parameter n must be int or passive of cast to int.")
33
if n <= 0:
34
raise ValueError("Parameter n must be greater or equal to one.")
35
36
i = 2
37
ans = 0
38
39
if n == 2:
40
return 2
41
42
while n > 2:
43
while n % i != 0:
44
i += 1
45
46
ans = i
47
48
while n % i == 0:
49
n = n / i
50
51
i += 1
52
53
return int(ans)
54
55
56
if __name__ == "__main__":
57
# print(solution(int(input().strip())))
58
import doctest
59
60
doctest.testmod()
61
print(solution(int(input().strip())))
Copied!
1
# Python3 program to add two numbers
2
3
number1 = input("First number: ")
4
number2 = input("\nSecond number: ")
Copied!
1
# Adding two numbers
2
# User might also enter float numbers
3
sum = float(number1) + float(number2)
Copied!
1
# Display the sum
2
# will print value in float
3
print("The sum of {0} and {1} is {2}".format(number1, number2, sum))
4
5
def sumOfSeries(n):
6
x = n * (n + 1) / 2
7
return (int)(x * x)
Copied!
1
# Driver Function
2
n = 5
3
print(sumOfSeries(n))
Copied!
1
# Program to find the ASCII value of the given character
2
3
c = "p"
4
print("The ASCII value of '" + c + "' is", ord(c))
5
6
"""
7
Problem:
8
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor
9
of a given number N?
10
11
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
12
"""
Copied!
1
# def solution(n: int) -> int:
2
def solution(n: int = 600851475143) -> int:
3
"""Returns the largest prime factor of a given number n.
4
>>> solution(13195)
5
29
6
>>> solution(10)
7
5
8
>>> solution(17)
9
17
10
>>> solution(3.4)
11
3
12
>>> solution(0)
13
Traceback (most recent call last):
14
...
15
ValueError: Parameter n must be greater or equal to one.
16
>>> solution(-17)
17
Traceback (most recent call last):
18
...
19
ValueError: Parameter n must be greater or equal to one.
20
>>> solution([])
21
Traceback (most recent call last):
22
...
23
TypeError: Parameter n must be int or passive of cast to int.
24
>>> solution("asd")
25
Traceback (most recent call last):
26
...
27
TypeError: Parameter n must be int or passive of cast to int.
28
"""
29
try:
30
n = int(n)
31
except (TypeError, ValueError):
32
raise TypeError("Parameter n must be int or passive of cast to int.")
33
if n <= 0:
34
raise ValueError("Parameter n must be greater or equal to one.")
35
36
i = 2
37
ans = 0
38
39
if n == 2:
40
return 2
41
42
while n > 2:
43
while n % i != 0:
44
i += 1
45
46
ans = i
47
48
while n % i == 0:
49
n = n / i
50
51
i += 1
52
53
return int(ans)
54
55
56
if __name__ == "__main__":
57
# print(solution(int(input().strip())))
58
import doctest
59
60
doctest.testmod()
61
print(solution(int(input().strip())))
62
63
import time
64
65
pwd = "AKS2608" # any password u want to set
66
67
68
def IInd_func():
69
count1 = 0
70
for j in range(5):
71
a = 0
72
count = 0
73
user_pwd = input("") # password you remember
74
for i in range(len(pwd)):
75
if user_pwd[i] == pwd[a]: # comparing remembered pwd with fixed pwd
76
a += 1
77
count += 1
78
if count == len(pwd):
79
print("correct pwd")
80
break
81
else:
82
count1 += 1
83
print("not correct")
84
if count1 == 5:
85
time.sleep(30)
86
IInd_func()
87
88
89
IInd_func()
Copied!
1
# This program adds two numbers
2
3
num1 = 1.5
4
num2 = 6.3
Copied!
1
# Add two numbers
2
sum = num1 + num2
Copied!
1
# Display the sum
2
print("The sum of {0} and {1} is {2}".format(num1, num2, sum))
3
4
class Node:
5
def __init__(self, data):
6
self.data = data
7
self.next = None
8
9
10
class Linked_List:
11
def __init__(self):
12
self.head = None
13
14
def Insert_At_Beginning(self, new_data):
15
new_node = Node(new_data)
16
if self.head is None:
17
self.head = new_node
18
return
19
new_node.next = self.head
20
self.head = new_node
21
22
def Add_two_no(self, First, Second):
23
prev = None
24
temp = None
25
carry = 0
26
while First is not None or Second is not None:
27
first_data = 0 if First is None else First.data
28
second_data = 0 if Second is None else Second.data
29
Sum = carry + first_data + second_data
30
carry = 1 if Sum >= 10 else 0
31
Sum = Sum if Sum < 10 else Sum % 10
32
temp = Node(Sum)
33
if self.head is None:
34
self.head = temp
35
else:
36
prev.next = temp
37
prev = temp
38
if First is not None:
39
First = First.next
40
if Second is not None:
41
Second = Second.next
42
if carry > 0:
43
temp.next = Node(carry)
44
45
def Display(self):
46
temp = self.head
47
while temp:
48
print(temp.data, "->", end=" ")
49
temp = temp.next
50
print("None")
51
52
53
if __name__ == "__main__":
54
First = Linked_List()
55
Second = Linked_List()
56
First.Insert_At_Beginning(6)
57
First.Insert_At_Beginning(4)
58
First.Insert_At_Beginning(9)
59
60
Second.Insert_At_Beginning(2)
61
Second.Insert_At_Beginning(2)
62
63
print("First Linked List: ")
64
First.Display()
65
print("Second Linked List: ")
66
Second.Display()
67
68
Result = Linked_List()
69
Result.Add_two_no(First.head, Second.head)
70
print("Final Result: ")
71
Result.Display()
Copied!
1
# This program adds two numbers
2
3
num1 = 1.5
4
num2 = 6.3
Copied!
1
# Add two numbers
2
sum = num1 + num2
Copied!
1
# Display the sum
2
print("The sum of {0} and {1} is {2}".format(num1, num2, sum))
3
4
a = 5
5
b = 6
6
c = 7
7
# a = float(input('Enter first side: '))
8
# b = float(input('Enter second side: '))
9
# c = float(input('Enter third side: '))
Copied!
1
# calculate the semi-perimeter
2
s = (a + b + c) / 2
Copied!
1
# calculate the area
2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
3
print("The area of the triangle is %0.2f" % area)
4
5
a = 5
6
b = 6
7
c = 7
8
# a = float(input('Enter first side: '))
9
# b = float(input('Enter second side: '))
10
# c = float(input('Enter third side: '))
Copied!
1
# calculate the semi-perimeter
2
s = (a + b + c) / 2
Copied!
1
# calculate the area
2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
3
print("The area of the triangle is %0.2f" % area)
Copied!
1
# Python Program to find the area of triangle when all three side-lengths are known!
2
3
a = 5
4
b = 6
5
c = 7
Copied!
1
# Uncomment below to take inputs from the user
2
# a = float(input('Enter first side: '))
3
# b = float(input('Enter second side: '))
4
# c = float(input('Enter third side: '))
Copied!
1
# calculate the semi-perimeter
2
s = (a + b + c) / 2
Copied!
1
# calculate the area
2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
3
print("The area of the triangle is %0.2f" % area)
4
5
num = int(input("enter 1-digit number:"))
6
f = num
7
sum = 0
8
while f > 0:
9
a = f % 10
10
f = int(f / 10)
11
sum = sum + (a ** 3)
12
if sum == num:
13
print("it is an armstrong number:", num)
14
else:
15
print("it is not an armstrong number:", num)
16
17
num=int(input("Enter a number:"))
18
sum=0
19
temp=num
20
while temp>0:
21
digit=temp%10
22
sum+=digit**3
23
temp//=10
24
if num==sum:
25
print(num,"is an Armstrong number")
26
else:
27
print(num,"is not an Armstrong number")
28
29
from tkinter import Tk, Canvas
30
31
from PIL.Image import open as openImage
32
from PIL.ImageTk import PhotoImage
33
34
35
class Background(Canvas):
36
"""
37
Classe para gerar um plano de fundo animado
38
"""
39
40
__background = []
41
__stop = False
42
43
def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed=50):
44
45
# Verifica se o parâmetro tk_instance é uma instância de Tk
46
if not isinstance(tk_instance, Tk):
47
raise TypeError("The tk_instance argument must be an instance of Tk.")
48
49
# Recebe o caminho de imagem e a velocidade da animação
50
self.image_path = fp
51
self.animation_speed = animation_speed
52
53
# Recebe a largura e altura do widget
54
self.__width = geometry[0]
55
self.__height = geometry[1]
56
57
# Inicializa o construtor da classe Canvas
58
Canvas.__init__(
59
self, master=tk_instance, width=self.__width, height=self.__height
60
)
61
62
# Carrega a imagem que será usada no plano de fundo
63
self.__bg_image = self.getPhotoImage(
64
image_path=self.image_path,
65
width=self.__width,
66
height=self.__height,
67
closeAfter=True,
68
)[0]
69
70
# Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação
71
self.__background_default = self.create_image(
72
self.__width // 2, self.__height // 2, image=self.__bg_image
73
)
74
75
# Cria as imagens que serão utilizadas na animação do background
76
self.__background.append(
77
self.create_image(
78
self.__width // 2, self.__height // 2, image=self.__bg_image
79
)
80
)
81
self.__background.append(
82
self.create_image(
83
self.__width + (self.__width // 2),
84
self.__height // 2,
85
image=self.__bg_image,
86
)
87
)
88
89
def getBackgroundID(self):
90
"""
91
Retorna os id's das imagens de background
92
"""
93
return [self.__background_default, *self.__background]
94
95
@staticmethod
96
def getPhotoImage(
97
image=None, image_path=None, width=None, height=None, closeAfter=False
98
):
99
"""
100
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image
101
(photoImage, new, original)
102
103
@param image: Instância de PIL.Image.open
104
@param image_path: Diretório da imagem
105
@param width: Largura da imagem
106
@param height: Altura da imagem
107
@param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma
108
"""
109
110
if not image:
111
if not image_path:
112
return
113
114
# Abre a imagem utilizando o caminho dela
115
image = openImage(image_path)
116
117
# Será redimesionada a imagem somente se existir um width ou height
118
if not width:
119
width = image.width
120
if not height:
121
height = image.height
122
123
# Cria uma nova imagem já redimensionada
124
newImage = image.resize([width, height])
125
126
# Cria um photoImage
127
photoImage = PhotoImage(newImage)
128
129
# Se closeAfter for True, ele fecha as imagens
130
if closeAfter:
131
# Fecha a imagem nova
132
newImage.close()
133
newImage = None
134
135
# Fecha a imagem original
136
image.close()
137
image = None
138
139
# Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original
140
return photoImage, newImage, image
141
142
def reset(self):
143
"""
144
Método para resetar o background, apagando todos os itens que não sejam o plano de fundo
145
"""
146
147
# Deleta todos os itens do canvas
148
self.delete("all")
149
150
# Para a animação passando False para o atributo "stop"
151
self.__stop = False
152
153
# Limpa a lista de imagens usadas na animação
154
self.__background.clear()
155
156
# Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação
157
self.__background_default = self.create_image(
158
self.__width // 2, self.__height // 2, image=self.__bg_image
159
)
160
161
# Cria as imagens que serão utilizadas na animação do background
162
self.__background.append(
163
self.create_image(
164
self.__width // 2, self.__height // 2, image=self.__bg_image
165
)
166
)
167
self.__background.append(
168
self.create_image(
169
self.__width + (self.__width // 2),
170
self.__height // 2,
171
image=self.__bg_image,
172
)
173
)
174
175
def run(self):
176
"""
177
Método para iniciar a animação do background
178
"""
179
180
# Enquanto o atributo "stop" for False, a animação continuará em um loop infinito
181
if not self.__stop:
182
183
# Move as imagens de background na posição X
184
self.move(self.__background[0], -10, 0)
185
self.move(self.__background[1], -10, 0)
186
self.tag_lower(self.__background[0])
187
self.tag_lower(self.__background[1])
188
self.tag_lower(self.__background_default)
189
190
# Se a primeira imagem da lista tiver saído da área do widget, uma nova será criada depois da segunda imagem
191
if self.bbox(self.__background[0])[2] <= 0:
192
# Deleta a primeira imagem da lista (imagem que saiu da área do widget)
193
self.delete(self.__background[0])
194
self.__background.remove(self.__background[0])
195
196
# Cria uma nova imagem a partir da última imagem da animação
197
width = self.bbox(self.__background[0])[2] + self.__width // 2
198
self.__background.append(
199
self.create_image(width, self.__height // 2, image=self.__bg_image)
200
)
201
202
# Executa novamente o método depois de um certo tempo
203
self.after(self.animation_speed, self.run)
204
205
def stop(self):
206
"""
207
Método para parar a animação do background
208
"""
209
self.__stop = True
210
211
def base_check(xnumber, xbase):
212
for char in xnumber[len(xnumber ) -1]:
213
if int(char) >= int(xbase):
214
return False
215
return True
216
217
def convert_from_10(xnumber, xbase, arr, ybase):
218
if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8:
219
220
if xnumber == 0:
221
return arr
222
else:
223
quotient = int(xnumber) // int(xbase)
224
remainder = int(xnumber) % int(xbase)
225
arr.append(remainder)
226
dividend = quotient
227
convert_from_10(dividend, xbase, arr, base)
228
elif int(xbase) == 16:
229
if int(xnumber) == 0:
230
return arr
231
else:
232
quotient = int(xnumber) // int(xbase)
233
remainder = int(xnumber) % int(xbase)
234
if remainder > 9:
235
if remainder == 10: remainder = 'A'
236
if remainder == 11: remainder = 'B'
237
if remainder == 12: remainder = 'C'
238
if remainder == 13: remainder = 'D'
239
if remainder == 14: remainder = 'E'
240
if remainder == 15: remainder = 'F'
241
arr.append(remainder)
242
dividend = quotient
243
convert_from_10(dividend, xbase, arr, ybase)
244
def convert_to_10(xnumber, xbase, arr, ybase):
245
if int(xbase) == 10:
246
for char in xnumber:
247
arr.append(char)
248
flipped = arr[::-1]
249
ans = 0
250
j = 0
251
252
for i in flipped:
253
ans = ans + (int(i) * (int(ybase) ** j))
254
j = j + 1
255
return ans
256
arrayfrom = []
257
arrayto = []
258
is_base_possible = False
259
number = input("Enter the number you would like to convert: ")
260
261
while not is_base_possible:
262
base = input("What is the base of this number? ")
263
is_base_possible = base_check(number, base)
264
if not is_base_possible:
265
print(f"The number {number} is not a base {base} number")
266
base = input
267
else:
268
break
269
dBase = input("What is the base you would like to convert to? ")
270
if int(base) == 10:
271
convert_from_10(number, dBase, arrayfrom, base)
272
answer = arrayfrom[::-1] # reverses the array
273
print(f"In base {dBase} this number is: ")
274
print(*answer, sep='')
275
elif int(dBase) == 10:
276
answer = convert_to_10(number, dBase, arrayto, base)
277
print(f"In base {dBase} this number is: {answer} ")
278
else:
279
number = convert_to_10(number, 10, arrayto, base)
280
convert_from_10(number, dBase, arrayfrom, base)
281
answer = arrayfrom[::-1]
282
print(f"In base {dBase} this number is: ")
283
print(*answer, sep='')
284
© 2020 GitHub, Inc.
285
286
def base_check(xnumber, xbase):
287
for char in xnumber[len(xnumber ) -1]:
288
if int(char) >= int(xbase):
289
return False
290
return True
291
292
def convert_from_10(xnumber, xbase, arr, ybase):
293
if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8:
294
295
if xnumber == 0:
296
return arr
297
else:
298
quotient = int(xnumber) // int(xbase)
299
remainder = int(xnumber) % int(xbase)
300
arr.append(remainder)
301
dividend = quotient
302
convert_from_10(dividend, xbase, arr, base)
303
elif int(xbase) == 16:
304
if int(xnumber) == 0:
305
return arr
306
else:
307
quotient = int(xnumber) // int(xbase)
308
remainder = int(xnumber) % int(xbase)
309
if remainder > 9:
310
if remainder == 10: remainder = 'A'
311
if remainder == 11: remainder = 'B'
312
if remainder == 12: remainder = 'C'
313
if remainder == 13: remainder = 'D'
314
if remainder == 14: remainder = 'E'
315
if remainder == 15: remainder = 'F'
316
arr.append(remainder)
317
dividend = quotient
318
convert_from_10(dividend, xbase, arr, ybase)
319
def convert_to_10(xnumber, xbase, arr, ybase):
320
if int(xbase) == 10:
321
for char in xnumber:
322
arr.append(char)
323
flipped = arr[::-1]
324
ans = 0
325
j = 0
326
327
for i in flipped:
328
ans = ans + (int(i) * (int(ybase) ** j))
329
j = j + 1
330
return ans
331
arrayfrom = []
332
arrayto = []
333
is_base_possible = False
334
number = input("Enter the number you would like to convert: ")
335
336
while not is_base_possible:
337
base = input("What is the base of this number? ")
338
is_base_possible = base_check(number, base)
339
if not is_base_possible:
340
print(f"The number {number} is not a base {base} number")
341
base = input
342
else:
343
break
344
dBase = input("What is the base you would like to convert to? ")
345
if int(base) == 10:
346
convert_from_10(number, dBase, arrayfrom, base)
347
answer = arrayfrom[::-1] # reverses the array
348
print(f"In base {dBase} this number is: ")
349
print(*answer, sep='')
350
elif int(dBase) == 10:
351
answer = convert_to_10(number, dBase, arrayto, base)
352
print(f"In base {dBase} this number is: {answer} ")
353
else:
354
number = convert_to_10(number, 10, arrayto, base)
355
convert_from_10(number, dBase, arrayfrom, base)
356
answer = arrayfrom[::-1]
357
print(f"In base {dBase} this number is: ")
358
print(*answer, sep='')
359
© 2020 GitHub, Inc.
360
361
def pascal_triangle(lineNumber):
362
list1 = list()
363
list1.append([1])
364
i = 1
365
while i <= lineNumber:
366
j = 1
367
l = []
368
l.append(1)
369
while j < i:
370
l.append(list1[i - 1][j] + list1[i - 1][j - 1])
371
j = j + 1
372
l.append(1)
373
list1.append(l)
374
i = i + 1
375
return list1
376
377
378
def binomial_coef(n, k):
379
pascalTriangle = pascal_triangle(n)
380
return pascalTriangle[n][k - 1]
381
382
def pascal_triangle(lineNumber):
383
list1 = list()
384
list1.append([1])
385
i = 1
386
while i <= lineNumber:
387
j = 1
388
l = []
389
l.append(1)
390
while j < i:
391
l.append(list1[i - 1][j] + list1[i - 1][j - 1])
392
j = j + 1
393
l.append(1)
394
list1.append(l)
395
i = i + 1
396
return list1
397
398
399
def binomial_coef(n, k):
400
pascalTriangle = pascal_triangle(n)
401
return pascalTriangle[n][k - 1]
402
403
def Binary_Search(Test_arr, low, high, k):
404
if high >= low:
405
Mid = (low + high) // 2
406
if Test_arr[Mid] < k:
407
return Binary_Search(Test_arr, Mid + 1, high, k)
408
elif Test_arr[Mid] > k:
409
return Binary_Search(Test_arr, low, Mid - 1, k)
410
else:
411
return Mid
412
else:
413
return low
414
415
416
def Insertion_Sort(Test_arr):
417
for i in range(1, len(Test_arr)):
418
val = Test_arr[i]
419
j = Binary_Search(Test_arr[:i], 0, len(Test_arr[:i]) - 1, val)
420
Test_arr.pop(i)
421
Test_arr.insert(j, val)
422
return Test_arr
423
424
425
if __name__ == "__main__":
426
Test_list = input("Enter the list of Numbers: ").split()
427
Test_list = [int(i) for i in Test_list]
428
print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}")
Copied!
1
# Program to convert binary to decimal
2
3
4
def binaryToDecimal(binary):
5
"""
6
>>> binaryToDecimal(111110000)
7
496
8
>>> binaryToDecimal(10100)
9
20
10
>>> binaryToDecimal(101011)
11
43
12
"""
13
decimal, i, n = 0, 0, 0
14
while binary != 0:
15
dec = binary % 10
16
decimal = decimal + dec * pow(2, i)
17
binary = binary // 10
18
i += 1
19
print(decimal)
20
21
22
binaryToDecimal(100)
23
24
from threading import Thread
25
26
from Background import Background
27
from PIL.Image import open as openImage
28
from PIL.ImageTk import PhotoImage
29
30
31
class Bird(Thread):
32
"""
33
Classe para criar um pássaro
34
"""
35
36
__tag = "Bird"
37
__isAlive = None
38
__going_up = False
39
__going_down = 0
40
__times_skipped = 0
41
__running = False
42
43
decends = 0.00390625
44
climbsUp = 0.0911458333
45
46
def __init__(
47
self,
48
background,
49
gameover_function,
50
*screen_geometry,
51
fp="bird.png",
52
event="<Up>",
53
descend_speed=5
54
):
55
56
# Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamável
57
58
if not isinstance(background, Background):
59
raise TypeError(
60
"The background argument must be an instance of Background."
61
)
62
if not callable(gameover_function):
63
raise TypeError("The gameover_method argument must be a callable object.")
64
65
# Instância os parâmetros
66
self.__canvas = background
67
self.image_path = fp
68
self.__descend_speed = descend_speed
69
self.gameover_method = gameover_function
70
71
# Recebe a largura e altura do background
72
self.__width = screen_geometry[0]
73
self.__height = screen_geometry[1]
74
75
# Define a decida e subida do pássaro com base na altura do background
76
self.decends *= self.__height
77
self.decends = int(self.decends + 0.5)
78
self.climbsUp *= self.__height
79
self.climbsUp = int(self.climbsUp + 0.5)
80
81
# Invoca o método construtor de Thread
82
Thread.__init__(self)
83
84
# Calcula o tamanho do pássaro com base na largura e altura da janela
85
self.width = (self.__width // 100) * 6
86
self.height = (self.__height // 100) * 11
87
88
# Carrega e cria a imagem do pássaro no background
89
self.__canvas.bird_image = self.getPhotoImage(
90
image_path=self.image_path,
91
width=self.width,
92
height=self.height,
93
closeAfter=True,
94
)[0]
95
self.__birdID = self.__canvas.create_image(
96
self.__width // 2,
97
self.__height // 2,
98
image=self.__canvas.bird_image,
99
tag=self.__tag,
100
)
101
102
# Define evento para fazer o pássaro subir
103
self.__canvas.focus_force()
104
self.__canvas.bind(event, self.jumps)
105
self.__isAlive = True
106
107
def birdIsAlive(self):
108
"""
109
Método para verificar se o pássaro está vivo
110
"""
111
112
return self.__isAlive
113
114
def checkCollision(self):
115
"""
116
Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo
117
"""
118
119
# Recebe a posição do pássaro no background
120
position = list(self.__canvas.bbox(self.__tag))
121
122
# Se o pássaro tiver ultrapassado a borda de baixo do background, ele será declarado morto
123
if position[3] >= self.__height + 20:
124
self.__isAlive = False
125
126
# Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto
127
if position[1] <= -20:
128
self.__isAlive = False
129
130
# Dá uma margem de erro ao pássaro de X pixels
131
position[0] += int(25 / 78 * self.width)
132
position[1] += int(25 / 77 * self.height)
133
position[2] -= int(20 / 78 * self.width)
134
position[3] -= int(10 / 77 * self.width)
135
136
# Define os objetos a serem ignorados em colisões
137
ignored_collisions = self.__canvas.getBackgroundID()
138
ignored_collisions.append(self.__birdID)
139
140
# Verifica possíveis colisões com o pássaro
141
possible_collisions = list(self.__canvas.find_overlapping(*position))
142
143
# Remove das possíveis colisões os objetos ignorados
144
for _id in ignored_collisions:
145
try:
146
possible_collisions.remove(_id)
147
except:
148
continue
149
150
# Se houver alguma colisão o pássaro morre
151
if len(possible_collisions) >= 1:
152
self.__isAlive = False
153
154
return not self.__isAlive
155
156
def getTag(self):
157
"""
158
Método para retornar a tag do pássaro
159
"""
160
161
return self.__tag
162
163
@staticmethod
164
def getPhotoImage(
165
image=None, image_path=None, width=None, height=None, closeAfter=False
166
):
167
"""
168
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image
169
(photoImage, new, original)
170
171
@param image: Instância de PIL.Image.open
172
@param image_path: Diretório da imagem
173
@param width: Largura da imagem
174
@param height: Altura da imagem
175
@param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma
176
"""
177
178
if not image:
179
if not image_path:
180
return
181
182
# Abre a imagem utilizando o caminho dela
183
image = openImage(image_path)
184
185
# Será redimesionada a imagem somente se existir um width ou height
186
if not width:
187
width = image.width
188
if not height:
189
height = image.height
190
191
# Cria uma nova imagem já redimensionada
192
newImage = image.resize([width, height])
193
194
# Cria um photoImage
195
photoImage = PhotoImage(newImage)
196
197
# Se closeAfter for True, ele fecha as imagens
198
if closeAfter:
199
# Fecha a imagem nova
200
newImage.close()
201
newImage = None
202
203
# Fecha a imagem original
204
image.close()
205
image = None
206
207
# Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original
208
return photoImage, newImage, image
209
210
def jumps(self, event=None):
211
"""
212
Método para fazer o pássaro pular
213
"""
214
215
# Verifica se o pássaro saiu da área do background
216
self.checkCollision()
217
218
# Se o pássaro estiver morto, esse método não pode ser executado
219
if not self.__isAlive or not self.__running:
220
self.__going_up = False
221
return
222
223
# Declara que o pássaro está subindo
224
self.__going_up = True
225
self.__going_down = 0
226
227
# Move o pássaro enquanto o limite de subida por animação não tiver excedido
228
if self.__times_skipped < self.climbsUp:
229
230
# Move o pássaro para cima
231
self.__canvas.move(self.__tag, 0, -1)
232
self.__times_skipped += 1
233
234
# Executa o método novamente
235
self.__canvas.after(3, self.jumps)
236
237
else:
238
239
# Declara que o pássaro não está mais subindo
240
self.__going_up = False
241
self.__times_skipped = 0
242
243
def kill(self):
244
"""
245
Método para matar o pássaro
246
"""
247
248
self.__isAlive = False
249
250
def run(self):
251
"""
252
#Método para iniciar a animação do passáro caindo
253
"""
254
255
self.__running = True
256
257
# Verifica se o pássaro saiu da área do background
258
self.checkCollision()
259
260
# Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05
261
if self.__going_down < self.decends:
262
self.__going_down += 0.05
263
264
# Executa a animação de descida somente se o pássaro estiver vivo
265
if self.__isAlive:
266
267
# Executa a animação de descida somente se o pássaro não estiver subindo
268
if not self.__going_up:
269
# Move o pássaro para baixo
270
self.__canvas.move(self.__tag, 0, self.__going_down)
271
272
# Executa novamente o método
273
self.__canvas.after(self.__descend_speed, self.run)
274
275
# Se o pássaro estiver morto, será executado um método de fim de jogo
276
else:
277
self.__running = False
278
self.gameover_method()
279
280
from itertools import product
281
282
283
def findPassword(chars, function, show=50, format_="%s"):
284
285
password = None
286
attempts = 0
287
size = 1
288
stop = False
289
290
while not stop:
291
292
# Obtém todas as combinações possíveis com os dígitos do parâmetro "chars".
293
for pw in product(chars, repeat=size):
294
295
password = "".join(pw)
296
297
# Imprime a senha que será tentada.
298
if attempts % show == 0:
299
print(format_ % password)
300
301
# Verifica se a senha é a correta.
302
if function(password):
303
stop = True
304
break
305
else:
306
attempts += 1
307
size += 1
308
309
return password, attempts
310
311
312
def getChars():
313
"""
314
Método para obter uma lista contendo todas as
315
letras do alfabeto e números.
316
"""
317
chars = []
318
319
# Acrescenta à lista todas as letras maiúsculas
320
for id_ in range(ord("A"), ord("Z") + 1):
321
chars.append(chr(id_))
322
323
# Acrescenta à lista todas as letras minúsculas
324
for id_ in range(ord("a"), ord("z") + 1):
325
chars.append(chr(id_))
326
327
# Acrescenta à lista todos os números
328
for number in range(10):
329
chars.append(str(number))
330
331
return chars
Copied!
1
# Se este módulo não for importado, o programa será testado.
2
# Para realizar o teste, o usuário deverá inserir uma senha para ser encontrada.
3
4
if __name__ == "__main__":
5
6
import datetime
7
import time
8
9
# Pede ao usuário uma senha
10
pw = input("\n Type a password: ")
11
print("\n")
12
13
def testFunction(password):
14
global pw
15
if password == pw:
16
return True
17
else:
18
return False
19
20
# Obtém os dígitos que uma senha pode ter
21
chars = getChars()
22
23
t = time.process_time()
24
25
# Obtém a senha encontrada e o múmero de tentativas
26
password, attempts = findPassword(
27
chars, testFunction, show=1000, format_=" Trying %s"
28
)
29
30
t = datetime.timedelta(seconds=int(time.process_time() - t))
31
input(f"\n\n Password found: {password}\n Attempts: {attempts}\n Time: {t}\n")
32
33
def bubblesort(list):
34
35
# Swap the elements to arrange in order
36
for iter_num in range(len(list) - 1, 0, -1):
37
for idx in range(iter_num):
38
if list[idx] > list[idx + 1]:
39
temp = list[idx]
40
list[idx] = list[idx + 1]
41
list[idx + 1] = temp
42
43
44
list = [19, 2, 31, 45, 6, 11, 121, 27]
45
bubblesort(list)
46
print(list)
47
48
def bubble_sort(Lists):
49
for i in range(len(Lists)):
50
for j in range(len(Lists) - 1):
51
# We check whether the adjecent number is greater or not
52
if Lists[j] > Lists[j + 1]:
53
Lists[j], Lists[j + 1] = Lists[j + 1], Lists[j]
Copied!
1
# Lets the user enter values of an array and verify by himself/herself
2
array = []
3
array_length = int(
4
input(print("Enter the number of elements of array or enter the length of array"))
5
)
6
for i in range(array_length):
7
value = int(input(print("Enter the value in the array")))
8
array.append(value)
9
10
bubble_sort(array)
11
print(array)
12
13
def res(R1, R2):
14
sum = R1 + R2
15
if option == "series":
16
return sum
17
else:
18
return (R1 * R2) / (R1 + R2)
19
20
21
Resistance1 = int(input("Enter R1 : "))
22
Resistance2 = int(input("Enter R2 : "))
23
option = str(input("Enter series or parallel :"))
24
print("\n")
25
R = res(Resistance1, Resistance2)
26
print("The total resistance is", R)
27
28
def res(R1, R2):
29
sum = R1 + R2
30
if option == "series":
31
return sum
32
else:
33
return (R1 * R2) / (R1 + R2)
34
35
36
Resistance1 = int(input("Enter R1 : "))
37
Resistance2 = int(input("Enter R2 : "))
38
option = str(input("Enter series or parallel :"))
39
print("\n")
40
R = res(Resistance1, Resistance2)
41
print("The total resistance is", R)
42
43
from tkinter import *
44
import calendar
45
46
root = Tk()
47
# root.geometry("400x300")
48
root.title("Calendar")
Copied!
1
# Function
2
3
4
def text():
5
month_int = int(month.get())
6
year_int = int(year.get())
7
cal = calendar.month(year_int, month_int)
8
textfield.delete(0.0, END)
9
textfield.insert(INSERT, cal)
Copied!
1
# Creating Labels
2
label1 = Label(root, text="Month:")
3
label1.grid(row=0, column=0)
4
5
label2 = Label(root, text="Year:")
6
label2.grid(row=0, column=1)
Copied!
1
# Creating spinbox
2
month = Spinbox(root, from_=1, to=12, width=8)
3
month.grid(row=1, column=0, padx=5)
4
5
year = Spinbox(root, from_=2000, to=2100, width=10)
6
year.grid(row=1, column=1, padx=10)
Copied!
1
# Creating Button
2
button = Button(root, text="Go", command=text)
3
button.grid(row=1, column=2, padx=10)
Copied!
1
# Creating Textfield
2
textfield = Text(root, width=25, height=10, fg="red")
3
textfield.grid(row=2, columnspan=2)
4
5
6
root.mainloop()
7
8
from tkinter import *
9
import calendar
10
11
root = Tk()
12
# root.geometry("400x300")
13
root.title("Calendar")
Copied!
1
# Function
2
3
4
def text():
5
month_int = int(month.get())
6
year_int = int(year.get())
7
cal = calendar.month(year_int, month_int)
8
textfield.delete(0.0, END)
9
textfield.insert(INSERT, cal)
Copied!
1
# Creating Labels
2
label1 = Label(root, text="Month:")
3
label1.grid(row=0, column=0)
4
5
label2 = Label(root, text="Year:")
6
label2.grid(row=0, column=1)
Copied!
1
# Creating spinbox
2
month = Spinbox(root, from_=1, to=12, width=8)
3
month.grid(row=1, column=0, padx=5)
4
5
year = Spinbox(root, from_=2000, to=2100, width=10)
6
year.grid(row=1, column=1, padx=10)
Copied!
1
# Creating Button
2
button = Button(root, text="Go", command=text)
3
button.grid(row=1, column=2, padx=10)
Copied!
1
# Creating Textfield
2
textfield = Text(root, width=25, height=10, fg="red")
3
textfield.grid(row=2, columnspan=2)
4
5
6
root.mainloop()
7
8
import pyautogui # pip install pyautogui
9
from PIL import Image, ImageGrab # pip install pillow
Copied!
1
# from numpy import asarray
2
import time
3
4
5
def hit(key):
6
pyautogui.press(key)
7
return
8
9
10
def isCollide(data):
11
12
# for cactus
13
for i in range(329, 425):
14
for j in range(550, 650):
15
if data[i, j] < 100:
16
hit("up")
17
return
18
19
# Draw the rectangle for birds
20
# for i in range(310, 425):
21
# for j in range(390, 550):
22
# if data[i, j] < 100:
23
# hit("down")
24
# return
25
26
# return
27
28
29
if __name__ == "__main__":
30
print("Hey.. Dino game about to start in 3 seconds")
31
time.sleep(2)
32
# hit('up')
33
34
while True:
35
image = ImageGrab.grab().convert("L")
36
data = image.load()
37
isCollide(data)
38
39
# print(aarray(image))
40
41
# Draw the rectangle for cactus
42
# for i in range(315, 425):
43
# for j in range(550, 650):
44
# data[i, j] = 0
45
46
# # # # # Draw the rectangle for birds
47
# for i in range(310, 425):
48
# for j in range(390, 550):
49
# data[i, j] = 171
50
51
# image.show()
52
# break
53
54
import pyautogui # pip install pyautogui
55
from PIL import Image, ImageGrab # pip install pillow
Copied!
1
# from numpy import asarray
2
import time
3
4
5
def hit(key):
6
pyautogui.press(key)
7
return
8
9
10
def isCollide(data):
11
12
# for cactus
13
for i in range(329, 425):
14
for j in range(550, 650):
15
if data[i, j] < 100:
16
hit("up")
17
return
18
19
# Draw the rectangle for birds
20
# for i in range(310, 425):
21
# for j in range(390, 550):
22
# if data[i, j] < 100:
23
# hit("down")
24
# return
25
26
# return
27
28
29
if __name__ == "__main__":
30
print("Hey.. Dino game about to start in 3 seconds")
31
time.sleep(2)
32
# hit('up')
33
34
while True:
35
image = ImageGrab.grab().convert("L")
36
data = image.load()
37
isCollide(data)
38
39
# print(aarray(image))
40
41
# Draw the rectangle for cactus
42
# for i in range(315, 425):
43
# for j in range(550, 650):
44
# data[i, j] = 0
45
46
# # # # # Draw the rectangle for birds
47
# for i in range(310, 425):
48
# for j in range(390, 550):
49
# data[i, j] = 171
50
51
# image.show()
52
# break
53
54
import pickle
55
56
import tensorflow as tf
57
58
model = tf.keras.models.Sequential(
59
[
60
tf.keras.layers.Conv2D(
61
16, (3, 3), activation="relu", input_shape=(200, 200, 3)
62
),
63
tf.keras.layers.MaxPooling2D(2, 2),
64
tf.keras.layers.Conv2D(16, (3, 3), activation="relu"),
65
tf.keras.layers.MaxPooling2D(2, 2),
66
tf.keras.layers.Conv2D(16, (3, 3), activation="relu"),
67
tf.keras.layers.MaxPooling2D(2, 2),
68
tf.keras.layers.Flatten(),
69
tf.keras.layers.Dense(512, activation="relu"),
70
tf.keras.layers.Dense(1, activation="sigmoid"),
71
]
72
)
73
model.summary()
74
from tensorflow.keras.optimizers import RMSprop
75
76
model.compile(optimizer=RMSprop(lr=0.001), loss="binary_crossentropy", metrics=["acc"])
77
from tensorflow.keras.preprocessing.image import ImageDataGenerator
78
79
train_datagen = ImageDataGenerator(rescale=1 / 255)
80
train_generator = train_datagen.flow_from_directory(
81
"../Classification_human-or-horse",
82
target_size=(200, 200),
83
batch_size=222,
84
class_mode="binary",
85
)
86
model.fit_generator(train_generator, steps_per_epoch=6, epochs=1, verbose=1)
87
filename = "myTf1.sav"
88
pickle.dump(model, open(filename, "wb"))
89
90
from tkinter import Tk
91
from tkinter.filedialog import askopenfilename
92
from keras.preprocessing import image
93
import numpy as np
94
95
Tk().withdraw()
96
filename = askopenfilename()
97
print(filename)
98
img = image.load_img(filename, target_size=(200, 200))
99
x = image.img_to_array(img)
100
x = np.expand_dims(x, axis=0)
101
images = np.vstack([x])
102
classes = model.predict(images, batch_size=10)
103
print(classes[0])
104
if classes[0] > 0.5:
105
print(filename + " is a human")
106
else:
107
print(filename + " is a horse")
Copied!
1
# libraraies
2
3
import pytube
4
import sys
5
6
7
class YouTubeDownloder:
8
def __init__(self):
9
self.url = str(input("Enter the url of video : "))
10
self.youtube = pytube.YouTube(
11
self.url, on_progress_callback=YouTubeDownloder.onProgress
12
)
13
self.showTitle()
14
15
def showTitle(self):
16
print("title : {0}\n".format(self.youtube.title))
17
self.showStreams()
18
19
def showStreams(self):
20
self.streamNo = 1
21
for stream in self.youtube.streams:
22
print(
23
"{0} => resolution:{1}/fps:{2}/type:{3}".format(
24
self.streamNo, stream.resolution, stream.fps, stream.type
25
)
26
)
27
self.streamNo += 1
28
self.chooseStream()
29
30
def chooseStream(self):
31
self.choose = int(input("please select one : "))
32
self.validateChooseValue()
33
34
def validateChooseValue(self):
35
if self.choose in range(1, self.streamNo):
36
self.getStream()
37
else:
38
print("please enter a correct option on the list.")
39
self.chooseStream()
40
41
def getStream(self):
42
self.stream = self.youtube.streams[self.choose - 1]
43
self.getFileSize()
44
45
def getFileSize(self):
46
global file_size
47
file_size = self.stream.filesize / 1000000
48
self.getPermisionToContinue()
49
50
def getPermisionToContinue(self):
51
print(
52
"\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format(
53
self.youtube.title,
54
self.youtube.author,
55
file_size,
56
self.stream.resolution,
57
self.stream.fps,
58
)
59
)
60
if input("do you want it ?(defualt = (y)es) or (n)o ") == "n":
61
self.showStreams()
62
else:
63
self.main()
64
65
def download(self):
66
self.stream.download()
67
68
@staticmethod
69
def onProgress(stream=None, chunk=None, remaining=None):
70
file_downloaded = file_size - (remaining / 1000000)
71
print(
72
f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]",
73
end="\r",
74
)
75
76
def main(self):
77
try:
78
self.download()
79
except KeyboardInterrupt:
80
print("Canceled. ")
81
sys.exit(0)
82
83
84
if __name__ == "__main__":
85
try:
86
YouTubeDownloder()
87
except KeyboardInterrupt:
88
pass
89
except Exception as e:
90
print(e)
91
92
number = int(input())
93
94
95
counter = 0
96
while number > 0:
97
number = number // 10
98
print(number)
99
counter += 1
100
print("number of digits :", counter)
Copied!
1
# dictionary initialization using {}
2
mydict = {"a": 1, "b": 2}
Copied!
1
# add new (key,value) pair
2
mydict["c"] = 3
Copied!
1
# modify existing (key,value) pair
2
mydict["a"] = 5
Copied!
1
# remove (key,value) pair
2
mydict.pop("a")
Copied!
1
# get length of the dictionary
2
print(len(mydict))
Copied!
1
# iteration through keys
2
for key in mydict.keys():
3
print(key)
Copied!
1
# iteration through values
2
for value in mydict.values():
3
print(value)
Copied!
1
# iteration through (key,value) pairs
2
for key, value in mydict.items():
3
print(key, value)
Copied!
1
#!/usr/bin/env python2
2
# -*- coding:utf8 -*-
3
"""
4
A simple Python 3.4+ script to send a text message to a Free Mobile phone.
5
6
- Warning: it only works in France to a French number, using the mobile operator Free Mobile.
7
- Warning: some initial configuration is required before running this script (see the error messages).
8
- Copyright 2014-20 Lilian Besson
9
- License MIT.
10
11
Examples
12
--------
13
$ FreeSMS.py --help
14
Gives help
15
16
$ FreeSMS.py "I like using Python to send SMS to myself from my laptop -- and it's free thanks to Free Mobile !"
17
Will send a test message to your mobile phone.
18
19
20
- Last version? Take a look to the latest version at https://github.com/Naereen/FreeSMS.py
21
- Initial Copyright : José - Juin 2014 (http://eyesathome.free.fr/index.php/tag/freemobile/)
22
- License:
23
24
MIT License
25
26
Copyright (c) 2014-21 Lilian Besson (Naereen), https://github.com/Naereen
27
28
Permission is hereby granted, free of charge, to any person obtaining a copy
29
of this software and associated documentation files (the "Software"), to deal
30
in the Software without restriction, including without limitation the rights
31
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32
copies of the Software, and to permit persons to whom the Software is
33
furnished to do so, subject to the following conditions:
34
35
The above copyright notice and this permission notice shall be included in all
36
copies or substantial portions of the Software.
37
38
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44
SOFTWARE.
45
"""
46
47
from __future__ import print_function
Copied!
1
# Use sys.version to be compatible with Python 2
2
import sys
Copied!
1
# Use os.getenv to see try to emulate os.path.expanduser if needed
2
import os
Copied!
1
# Use time to sleep and get string for today current hour
2
import time
Copied!
1
# Use JSON to pretty print a dictionary
2
import json
Copied!
1
# Use base64 to not keep plaintext files of the number, username and password in your home
2
import base64
3
4
today = time.strftime("%H:%M:%S %Y-%m-%d")
5
6
try:
7
from os.path import expanduser
8
except ImportError:
9
print(
10
"Warning, os.path.expanduser is not available, trying to use os.getenv('USER') = {} ...".format(
11
os.getenv("USER")
12
)
13
)
14
15
def expanduser(s):
16
""" Try to simulate the os.path.expanduser function. """
17
return "/home/" + os.getenv("USER") + "/" + s
18
19
20
if sys.version_info < (3, 0):
21
from urllib import urlencode
22
from urllib2 import urlopen, HTTPError
23
else:
24
from urllib3.request import urlencode
25
from urllib.request import urlopen
26
from urllib.error import HTTPError
27
28
29
try:
30
try:
31
from ansicolortags import printc
32
except ImportError:
33
print(
34
"Optional dependancy (ansicolortags) is not available, using regular print function."
35
)
36
print(
37
" You can install it with : 'pip install ansicolortags' (or sudo pip)..."
38
)
39
from ANSIColors import printc
40
except ImportError:
41
print(
42
"Optional dependancy (ANSIColors) is not available, using regular print function."
43
)
44
print(
45
" You can install it with : 'pip install ANSIColors-balises' (or sudo pip)..."
46
)
47
48
def printc(*a, **kw):
49
""" Fake function printc.
50
51
ansicolortags or ANSIColors are not installed...
52
Install ansicolortags from pypi (with 'pip install ansicolortags')
53
"""
54
print(*a, **kw)
55
56
57
def testSpecialFile(name, number=""):
58
""" Test if the hidden file '~/.smsapifreemobile_name.b64' exists and decodes (base64) correctly.
59
"""
60
assert name in [
61
"number",
62
"user",
63
"password",
64
], "Error: unknown or incorrect value for 'name' for the function openSpecialFile(name) ..."
65
# printc("<cyan>Testing the hidden file <white>'<u>~/.smsapifreemobile_{}.b64<U>'<cyan>...<white>".format(name)) # DEBUG
66
try:
67
with open(
68
expanduser("~/") + ".smsapifreemobile_" + name + number + ".b64"
69
) as f:
70
variable = base64.b64decode(f.readline()[:-1])
71
while variable[-1] == "\n":
72
variable = variable[:-1]
73
return True
74
except OSError:
75
return False
76
77
78
def openSpecialFile(name, number=""):
79
""" Open the hidden file '~/.smsapifreemobile_name.b64', read and decode (base64) and return its content.
80
"""
81
assert name in [
82
"number",
83
"user",
84
"password",
85
], "Error: unknown or incorrect value for 'name' for the function openSpecialFile(name) ..."
86
printc(
87
"<cyan>Opening the hidden file <white>'<u>~/.smsapifreemobile_{}.b64<U>'<cyan>, read and decode (base64) and return its content...<white>".format(
88
name
89
)
90
)
91
try:
92
with open(
93
expanduser("~/") + ".smsapifreemobile_" + name + number + ".b64"
94
) as f:
95
variable = base64.b64decode(f.readline()[:-1])
96
while variable[-1] == "\n":
97
variable = variable[:-1]
98
return variable
99
except OSError:
100
printc(
101
"<red>Error: unable to read the file '~/.smsapifreemobile_{}.b64' ...<white>".format(
102
name
103
)
104
)
105
printc(
106
"<yellow>Please check that it is present, and if it not there, create it:<white>"
107
)
108
if name == "number":
109
print(
110
"To create '~/.smsapifreemobile_number.b64', use your phone number (like '0612345678', not wiht +33), and execute this command line (in a terminal):"
111
)
112
printc(
113
"<black>echo '0612345678' | base64 > '~/.smsapifreemobile_number.b64'<white>".format()
114
)
115
elif name == "user":
116
print(
117
"To create '~/.smsapifreemobile_user.b64', use your Free Mobile identifier (a 8 digit number, like '83123456'), and execute this command line (in a terminal):"
118
)
119
printc(
120
"<black>echo '83123456' | base64 > '~/.smsapifreemobile_user.b64'<white>".format()
121
)
122
elif name == "password":
123
print(
124
"To create '~/.smsapifreemobile_password.b64', go to this webpage, https://mobile.free.fr/moncompte/index.php?page=options&show=20 (after logging to your Free Mobile account), and copy the API key (a 14-caracters string on [a-zA-Z0-9]*, like 'H6ahkTABEADz5Z'), and execute this command line (in a terminal):"
125
)
126
printc(
127
"<black>echo 'H6ahkTABEADz5Z' | base64 > '~/.smsapifreemobile_password.b64<white>' ".format()
128
)
129
130
131
numbers = []
Copied!
1
#: Number (not necessary)
2
# number = base64.b64decode(open(expanduser('~') + ".smsapifreemobile_number.b64").readline()[:-1])
3
# if number[-1] == '\n':
4
# number = number[:-1]
5
number = openSpecialFile("number")
6
numbers.append(number)
7
8
if testSpecialFile("number", "2"):
9
number2 = openSpecialFile("number", "2")
10
numbers.append(number2)
Copied!
1
# Detect language
2
language = os.getenv("LANG")
3
language = language[0:2] if language else "fr"
Copied!
1
# Maximum size that can be sent
2
# XXX Reference: https://en.wikipedia.org/wiki/Short_Message_Service#Message_size
3
# "6 to 8 segment messages are the practical maximum"
4
MAX_SIZE = 4 * 159
5
STR_MAX_SIZE = "4*159"
6
7
8
if language == "fr":
9
errorcodes = {
10
400: "Un des paramètres obligatoires est manquant.",
11
402: "Trop de SMS ont été envoyés en trop peu de temps.",
12
403: """Le service n'est pas activé sur l'espace abonné, ou login / clé incorrect.
13
Allez sur '<black>https://mobile.free.fr/moncompte/index.php?page=options&show=20<white>' svp, et activez l'option correspondate.""",
14
500: "Erreur côté serveur. Veuillez réessayez ultérieurement.",
15
1: "Le SMS a été envoyé sur votre mobile ({}).".format(number)
16
if len(numbers) <= 1
17
else "Le SMS a été envoyé sur vos numéros ({}).".format(numbers),
18
"toolong": "<red>Attention<white> : le message est trop long (+ de <black>{}<white> caracters, soit plus de 3 SMS).".format(
19
STR_MAX_SIZE
20
),
21
}
22
else:
23
errorcodes = {
24
400: "One of the necessary parameter is missing.",
25
402: "Too many SMSs has been sent in a short time (you might be a spammer!).",
26
403: """Access denied: the service might not be activated on the online personnal space, or login/password is wrong.
27
Please go on '<black>https://mobile.free.fr/moncompte/index.php?page=options&show=20<white>' please, and enable the corresponding option.""",
28
500: "Error from the server side. Please try again later.",
29
1: "The SMS has been sent to your mobile ({}).".format(number)
30
if len(numbers) <= 1
31
else "The SMS has been sent to all your mobile numbers ({}).".format(numbers),
32
"toolong": "<red>Warning<white>: message is too long (more than <black>{}<white> caracters, so more than 3 SMS).".format(
33
STR_MAX_SIZE
34
),
35
}
36
37
38
def send_sms(text="Empty!", secured=True, sleep_duration=0):
39
""" Sens a free SMS to the user identified by [user], with [password].
40
41
:user: Free Mobile id (of the form [0-9]{8}),
42
:password: Service password (of the form [a-zA-Z0-9]{14}),
43
:text: The content of the message (a warning is displayed if the message is bigger than 480 caracters)
44
:secured: True to use HTTPS, False to use HTTP.
45
46
Returns a boolean and a status string.
47
"""
48
# DONE split the text into smaller pieces if length is too big (automatically, or propose to do it ?)
49
if len(text) > MAX_SIZE:
50
printc(errorcodes["toolong"])
51
nb_sub_messages = len(text) / MAX_SIZE
52
printc(
53
"\n<red>Warning<white>: message will be split in <red>{} piece{}<white> of size smaller than <black>{} characters<white>...".format(
54
nb_sub_messages + 1, "s" if nb_sub_messages > 0 else "", MAX_SIZE
55
)
56
)
57
printc(
58
" <magenta>Note that new lines and other information can be lost!<white>"
59
)
60
for i, index in enumerate(range(0, len(text), MAX_SIZE)):
61
answer = send_sms(text[index : index + MAX_SIZE])
62
printc(
63
"For piece #{} of the message, the answer is:\n <magenta>{}<white>...\n".format(
64
i + 1, answer[1]
65
)
66
)
67
return answer
68
# raise ValueError(errorcodes["toolong"])
69
70
# Read user and password
71
72
users = []
73
#: Identification Number free mobile
74
user = openSpecialFile("user")
75
users.append(user)
76
if testSpecialFile("user", "2"):
77
user2 = openSpecialFile("user", "2")
78
users.append(user2)
79
80
passwords = []
81
#: Password
82
password = openSpecialFile("password")
83
passwords.append(password)
84
if testSpecialFile("password", "2"):
85
password2 = openSpecialFile("password", "2")
86
passwords.append(password2)
87
88
printc("\n<green>Your message is:<white>\n<yellow>" + text + "<white>")
89
url = "https" if secured else "http"
90
91
# Sending to all the numbers
92
results = []
93
94
for (user, password) in zip(users, passwords):
95
dictQuery = {"user": user, "pass": password, "msg": text}
96
string_query = json.dumps(dictQuery, sort_keys=True, indent=4)
97
string_query = string_query.replace(password, "*" * len(password))
98
printc(
99
"\nThe web-based query to the Free Mobile API (<u>{}://smsapi.free-mobile.fr/sendmsg?query<U>) will be based on:\n{}.".format(
100
url, string_query
101
)
102
)
103
if sleep_duration > 0:
104
printc(
105
"\nSleeping for <red>{}<reset><white> seconds before querying the API...".format(
106
sleep_duration
107
)
108
)
109
try:
110
time.sleep(sleep_duration)
111
except KeyboardInterrupt as e:
112
printc(
113
"<red>You interrupted the process of sending this message, skipping to next one (or stopping now)...<reset><white>"
114
)
115
else:
116
printc(
117
"\nDone sleeping for <red>{}<reset><white> seconds, it's time to query the API !".format(
118
sleep_duration
119
)
120
)
121
122
query = urlencode(dictQuery)
123
url += "://smsapi.free-mobile.fr/sendmsg?{}".format(query)
124
125
try:
126
urlopen(url)
127
results.append((0, errorcodes[1]))
128
except HTTPError as e:
129
if hasattr(e, "code"):
130
results.append((e.code, errorcodes[e.code]))
131
else:
132
print("Unknown error...")
133
results.append((2, "Unknown error..."))
134
135
# Now we return the list of results
136
return results
137
138
139
def main(argv):
140
""" Main function. Use the arguments of the command line (sys.argv).
141
"""
142
# TODO use docopt to handle the command line arguments! Cf. http://docopt.org/
143
# TODO can docopt handle a cli documentation with ansicolortags tags in it? Cf. http://ansicolortags.rtfd.io/
144
# Manual handing of the command line arguments
145
if "-h" in argv or "--help" in argv:
146
printc(
147
"""
148
<green>FreeSMS.py<white> --help|-h | -f file | [--sleep] body of the message
149
150
A simple Python script to send a text message to a Free Mobile phone.
151
The message should be smaller than 480 caracters.
152
153
<u>Examples:<U>
154
<black>$ FreeSMS.py --help<white>
155
Print this help message!
156
157
<black>$ FreeSMS.py -f MyMessageFile.txt<white>
158
Try to send the content of the file MyMessageFile.txt.
159
160
<black>$ FreeSMS.py "I like using Python to send me SMS from my laptop -- and it"s free thanks to Free !"<white>
161
Will send a test message to your mobile phone.
162
163
<black>$ FreeSMS.py --sleep 1 "This option makes the script sleep for one minute"<white>
164
Sleep one minute.
165
166
<magenta>Copyright 2014-21 Lilian Besson (License MIT)<white>
167
<b>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.<reset><white>
168
"""
169
)
170
return [(0, None)]
171
172
sleep = False
173
sleep_duration = 15 # in seconds
174
if "--sleep" in argv:
175
sleep = True
176
index = argv.index("--sleep")
177
if index + 1 < len(argv):
178
try:
179
sleep_duration = int(argv[index + 1])
180
except:
181
printc(
182
"<red>Unable to get a sleep duration value from the command line argument ('{}' does not convert to an integer).".format(
183
argv[index + 1]
184
)
185
) # DEBUG
186
else:
187
argv.pop(index) # remove sleep_duration
188
argv.pop(index) # remove "--sleep"
189
190
if "-f" in argv:
191
try:
192
with open(argv[argv.index("-f") + 1], "r") as filename:
193
text = "".join(filename.readlines())[:-1]
194
except Exception as e:
195
print(e)
196
print("Trying to use the rest of the arguments to send the text message...")
197
text = " ".join(argv)
198
else:
199
if argv:
200
# Text of the SMS
201
if isinstance(argv, list):
202
text = " ".join(argv)
203
elif isinstance(argv, str):
204
text = argv
205
else:
206
printc(
207
"<Warning>argv seems to be of unknown type (not list, not str, but {}) ...".format(
208
type(argv)
209
)
210
)
211
text = argv
212
text = text.replace("\\n", "\n")
213
# Durty hack to have true new lines in the message
214
else:
215
text = """Test SMS sent from {machinename} with FreeSMS.py (the {date}).
216
217
(a Python 2.7+ / 3.4+ script by Lilian Besson, open source, you can find the code
218
at https://github.com/Naereen/FreeSMS.py
219
or https://perso.crans.org/besson/bin/FreeSMS.py)
220
221
For any issues, reach me by email at jarvis[at]crans[dot]org !"""
222
# FIXED Check that this is working correctly!
223
machinename = "jarvis" # Default name!
224
try:
225
machinename = open("/etc/hostname").readline()[:-1]
226
except OSError:
227
print(
228
"Warning: unknown machine name (file '/etc/hostname' not readable?)..."
229
)
230
machinename = "unknown machine"
231
text = text.format(date=today, machinename=machinename)
232
text = text.replace("[at]", "@").replace("[dot]", ".")
233
234
answers = send_sms(text, sleep_duration=sleep_duration)
235
return answers
236
237
238
if __name__ == "__main__":
239
# from doctest import testmod # DEBUG ?
240
# testmod(verbose=False) # DEBUG ?
241
results = main(sys.argv[1:])
242
first_result = results[0]
243
code, message = first_result
244
sys.exit(int(code))
245
246
def add(param1, param2):
247
return param1 + param2
Copied!
backpedal.py
623B
Binary
bfs_search_dict.py
689B
Binary
bfs_paths_dict.py
694B
Binary
bfs_search_grid.py
938B
Binary
bipartite_matching_single.py
712B
Binary
bisect_search.py
631B
Binary
bst_make_balanced_recur.py
587B
Binary
bt_inorder_traversal_recur.py
446B
Binary
bt_level_order_traversal_iter.py
986B
Binary
celebrity.py
566B
Binary
counting_sort_dict.py
460B
Binary
counting_sort_list.py
610B
Binary
dfs_component_dict.py
531B
Binary
selection_sort_recur.py
468B
Binary
selection_sort_iter.py
709B
Binary
dijkstras_path_pq.py
1KB
Binary
dijkstras_distances_min.py
1KB
Binary
quicksort.py
600B
Binary
counting_sort_list.py
610B
Binary
dfs_component_dict.py
531B
Binary
dfs_component_dict_recur.py
641B
Binary
Last modified 3mo ago
Export as PDF
Copy link